package org.example.springbootblog.common.pojo.utils;


import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;


import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class JwtUtil {

    private static final String secret = "5A0eXIRbAap/mJRWNqgIU9vkXNOoJlp3hDir5O/Ezw4=";
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));   // 根据上面字符串 根据编码生成签名

    //24小时过期
    private static final long expiration = 24 * 60 * 60 * 1000;
    //1.生成token
    public static String getToken(Map<String,Object> map){
        //签名
        return Jwts.builder()
                .setClaims(map)
                .signWith(key)
                .setIssuedAt(new Date())  //签发日期
                .setExpiration(new Date(System.currentTimeMillis()+expiration))  //过期日期
                .compact();

    }


    //2。校验token
    public static Claims parseToken(String token){
        if (!StringUtils.hasLength(token)) {
            return null;
        }

        //Jwt解析器
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = null;
        try {
             body = build.parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e) {
            log.error("token过期，token:{}",token);
            return null;
        }catch (SignatureException e) {
            log.error("签名不匹配，token:{}",token);
            return null;
        }catch (Exception e) {
            log.error("token解析失败，token：{}",token);
            return null;
        }
        return body;
    }
}
